package com.atguigu.dga230315.governance.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class TreadDemo {
    //声明连接池
    //参数说明：1.有几个线程 2.最大的容量 3.检查活跃的周期看链接是否还有人用 4.时间单位 5.队列
    static ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(100,100,60, TimeUnit.SECONDS,new LinkedBlockingDeque<>());


    public static void main(String[] args) {
        System.out.println("当前时间：" + System.currentTimeMillis());

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
        Integer sum = 0;

/*        for (Integer integer : list) {
            try {
                Thread.sleep(2000);
                sum += integer * integer;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }*/


        //使用异步编排进行优化
        ArrayList<CompletableFuture<Integer>> completableFutureArrayList = new ArrayList<>();

        for (Integer integer : list) {

            //期货
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {
                    try {
                        Thread.sleep(2000); //假定 计算逻辑复杂 每次需要两秒才计算完
                        return integer * integer;
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            },threadPoolExecutor);
            //收集每次平方操作后的结果
            completableFutureArrayList.add(completableFuture);
        }

        //获取所有的计算结果
        List<Integer> integerList = completableFutureArrayList.stream().map(result -> result.join()).collect(Collectors.toList());

        for (Integer integer : integerList) {
            sum += integer;
        }


        System.out.println(sum);
        System.out.println("结束时间：" + System.currentTimeMillis());
    }
}
